package models

import "gorm.io/gorm"

type User struct {
	gorm.Model
	Username string `gorm:"type:varchar(30)"json:"username"`
	Password string `gorm:"type:varchar(225)"json:"password"`
}

type UserRole struct {
	gorm.Model
	Uid int `gorm:"type:char(11)"json:"uid"`
	Rid int `gorm:"type:char(11)"json:"rid"`
}

type Role struct {
	gorm.Model
	Rolename string `gorm:"type:varchar(30)"json:"rolename"`
}
type RoleQuan struct {
	gorm.Model
	Qid int `gorm:"type:char(11)"json:"qid"`
	Rid int `gorm:"type:char(11)"json:"rid"`
}

type Quan struct {
	gorm.Model
	Quanname string `gorm:"type:varchar(30)"json:"quanname"`
}

type Compans struct {
	gorm.Model
	Compansname string `gorm:"type:varchar(30)"json:"compansname"`
}

type Order struct {
	gorm.Model
	Ordersname string `gorm:"type:varchar(30)"json:"ordersname"`
	Cid        int    `gorm:"type:char(11)"json:"cid"`
	Tid        int    `gorm:"type:char(11)"json:"tid"`
}

type Types struct {
	gorm.Model
	Typesname string `gorm:"type:varchar(30)"json:"typesname"`
}

func (*User) Dengs(username string, user *User) error {
	return DB.Where("username = ?", username).First(&user).Error
}

func (*RoleQuan) RoleQuanAdd(data *RoleQuan) error {
	tx := DB.Begin()
	err := tx.Create(data).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	tx.Commit()
	return err
}

func (r *Role) Rolelist(uid int) error {
	err := DB.Table("roles").
		Joins("LEFT JOIN user_roles on user_roles.rid=roles.id").
		Where("user_roles.uid=?", uid).
		Find(&r).Error
	return err
}

func (q *Quan) Quanlist(rid int) error {
	err := DB.Table("quans").
		Joins("LEFT JOIN role_quans on role_quans.qid=quans.id").
		Where("role_quans.rid=?", rid).
		Find(&q).Error
	return err
}
func (*Compans) CompansAdds(compans *Compans) error {
	tx := DB.Begin()
	err := tx.Debug().Create(compans).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	tx.Commit()
	return err
}
func (*Order) OrderAdds(order *Order) error {
	tx := DB.Begin()
	err := tx.Debug().Create(&order).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	tx.Commit()
	return err
}
